package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.RatingService;
import util.RegexUtil;
import ex.DatabaseException;
import ex.RatingException;

public class Rating extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RatingService rService=new RatingService();
		String to=request.getParameter("to");
		if(to=="user")
		{
			try{
				String rate=request.getParameter("selrate");
				if(!RegexUtil.isParsableToInt(rate) || Integer.parseInt(rate)<1 || Integer.parseInt(rate)>5)
					throw new RatingException("Rating is not valid!");
				
				HttpSession session = request.getSession();
				if(session!=null){					
					if(session.getAttribute("user")!=null){
						domain.User user=(domain.User)session.getAttribute("user");
						rService.rateUser(user, Integer.parseInt(rate));
						request.setAttribute("rate", (int)user.getRating());
						request.setAttribute("user", user);
					}
				}
			}
			catch (RatingException e) {
				request.setAttribute("error", e.getMessage());
			}
			catch (DatabaseException e) {
				request.setAttribute("error", e.getMessage());
			}
			catch (Exception e) {
				request.setAttribute("error", "A general error occured");
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
	}

}
